<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

interface MonthlyCountStats {
  [key: string]: number
}

interface MonthlyCostStats {
  [key: string]: number
}

const repairApi = {
  getMonthlyCountStats: () => {
    return request<MonthlyCountStats>({
      method: 'GET',
      url: '/repair/stats/monthlyCount'
    })
  },
  
  getMonthlyCostStats: () => {
    return request<MonthlyCostStats>({
      method: 'GET',
      url: '/repair/stats/monthlyCost'
    })
  }
}

const countChartRef = ref<HTMLElement | null>(null)
const costChartRef = ref<HTMLElement | null>(null)
const combinedChartRef = ref<HTMLElement | null>(null)

const getMonthlyCountStats = async () => {
  try {
    const response = await repairApi.getMonthlyCountStats()
    initCountChart(response.data)
  } catch (error) {
    ElMessage.error('获取维修次数统计失败')
    console.error(error)
  }
}

const getMonthlyCostStats = async () => {
  try {
    const response = await repairApi.getMonthlyCostStats()
    initCostChart(response.data)
    // 同时初始化组合图表
    if (response.data && countChartRef.value) {
      const countResponse = await repairApi.getMonthlyCountStats()
      initCombinedChart(countResponse.data, response.data)
    }
  } catch (error) {
    ElMessage.error('获取维修成本统计失败')
    console.error(error)
  }
}

const initCountChart = (data: MonthlyCountStats) => {
  if (!countChartRef.value) return
  
  const chart = echarts.init(countChartRef.value)
  const months = Object.keys(data).sort()
  const counts = months.map(month => data[month])
  
  const option = {
    backgroundColor: 'rgba(240, 248, 240, 0.9)',
    title: {
      text: '月度维修次数统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#2c3e50'
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(44, 62, 80, 0.8)',
      textStyle: { color: '#fff' },
      formatter: '{b}<br/>次数: {c}',
      padding: 10,
      extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLine: {
        lineStyle: {
          color: '#bdc3c7'
        }
      },
      axisLabel: {
        color: '#7f8c8d',
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '维修次数',
      nameTextStyle: {
        color: '#7f8c8d'
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(189, 195, 199, 0.3)'
        }
      },
      axisLabel: {
        color: '#7f8c8d',
        formatter: '{value}'
      }
    },
    series: [{
      name: '维修次数',
      data: counts,
      type: 'bar',
      barWidth: '40%',
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#8e44ad' },
          { offset: 1, color: '#9b59b6' }
        ]),
        borderRadius: [4, 4, 0, 0],
        shadowColor: 'rgba(0, 0, 0, 0.3)',
        shadowBlur: 5,
        shadowOffsetY: 3
      },
      label: {
        show: true,
        position: 'top',
        color: '#8e44ad',
        fontWeight: 'bold'
      },
      emphasis: {
        itemStyle: {
          shadowColor: 'rgba(0, 0, 0, 0.5)',
          shadowBlur: 10
        }
      }
    }]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const initCostChart = (data: MonthlyCostStats) => {
  if (!costChartRef.value) return
  
  const chart = echarts.init(costChartRef.value)
  const months = Object.keys(data).sort()
  const costs = months.map(month => data[month])
  
  const option = {
    backgroundColor: 'rgba(240, 248, 240, 0.9)',
    title: {
      text: '月度维修成本统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#2c3e50'
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(44, 62, 80, 0.8)',
      textStyle: { color: '#fff' },
      formatter: (params: any) => {
        return `${params[0].axisValue}<br/>成本: ¥${params[0].data.toLocaleString()}`
      },
      padding: 10,
      extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLine: {
        lineStyle: {
          color: '#bdc3c7'
        }
      },
      axisLabel: {
        color: '#7f8c8d',
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '维修成本(元)',
      nameTextStyle: {
        color: '#7f8c8d'
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(189, 195, 199, 0.3)'
        }
      },
      axisLabel: {
        color: '#7f8c8d',
        formatter: (value: number) => {
          if (value >= 10000) {
            return `${(value / 10000).toFixed(1)}万`
          }
          return value.toLocaleString()
        }
      }
    },
    series: [{
      name: '维修成本',
      data: costs,
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 10,
      showSymbol: false,
      lineStyle: {
        width: 4,
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          { offset: 0, color: '#e74c3c' },
          { offset: 1, color: '#c0392b' }
        ]),
        shadowColor: 'rgba(0, 0, 0, 0.3)',
        shadowBlur: 10,
        shadowOffsetY: 5
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(231, 76, 60, 0.4)' },
          { offset: 1, color: 'rgba(231, 76, 60, 0.05)' }
        ])
      },
      itemStyle: {
        color: '#e74c3c',
        borderWidth: 2,
        borderColor: '#fff'
      },
      label: {
        show: true,
        position: 'top',
        formatter: (params: any) => {
          return `¥${params.value.toLocaleString()}`
        },
        color: '#e74c3c',
        fontWeight: 'bold'
      },
      emphasis: {
        focus: 'series',
        scale: true
      }
    }]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
  
  chart.on('mouseover', (params) => {
    if (params.componentType === 'series') {
      chart.setOption({
        series: [{
          showSymbol: true
        }]
      })
    }
  })
  
  chart.on('mouseout', (params) => {
    if (params.componentType === 'series') {
      chart.setOption({
        series: [{
          showSymbol: false
        }]
      })
    }
  })
}

const initCombinedChart = (countData: MonthlyCountStats, costData: MonthlyCostStats) => {
  if (!combinedChartRef.value) return
  
  const chart = echarts.init(combinedChartRef.value)
  const months = Object.keys(countData).sort()
  const counts = months.map(month => countData[month])
  const costs = months.map(month => costData[month])
  
  const option = {
    backgroundColor: 'rgba(240, 248, 240, 0.9)',
    title: {
      text: '维修次数与成本对比',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#2c3e50'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      backgroundColor: 'rgba(44, 62, 80, 0.8)',
      textStyle: { color: '#fff' },
      padding: 10,
      extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);',
      formatter: (params: any) => {
        return `
          ${params[0].axisValue}<br/>
          ${params[0].marker} ${params[0].seriesName}: ${params[0].value}<br/>
          ${params[1].marker} ${params[1].seriesName}: ¥${params[1].value.toLocaleString()}
        `
      }
    },
    legend: {
      data: ['维修次数', '维修成本'],
      top: 25,
      textStyle: {
        color: '#7f8c8d'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: months,
        axisPointer: {
          type: 'shadow'
        },
        axisLine: {
          lineStyle: {
            color: '#bdc3c7'
          }
        },
        axisLabel: {
          color: '#7f8c8d',
          rotate: 45
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '维修次数',
        nameTextStyle: {
          color: '#8e44ad'
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(189, 195, 199, 0.3)'
          }
        },
        axisLabel: {
          color: '#7f8c8d',
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '维修成本(元)',
        nameTextStyle: {
          color: '#e74c3c'
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          color: '#7f8c8d',
          formatter: (value: number) => {
            if (value >= 10000) {
              return `${(value / 10000).toFixed(1)}万`
            }
            return value.toLocaleString()
          }
        }
      }
    ],
    series: [
      {
        name: '维修次数',
        type: 'bar',
        barWidth: '40%',
        data: counts,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#8e44ad' },
            { offset: 1, color: '#9b59b6' }
          ]),
          borderRadius: [4, 4, 0, 0],
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          shadowBlur: 5,
          shadowOffsetY: 3
        },
        label: {
          show: true,
          position: 'top',
          color: '#8e44ad',
          fontWeight: 'bold'
        }
      },
      {
        name: '维修成本',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        data: costs,
        lineStyle: {
          width: 4,
          color: '#e74c3c',
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          shadowBlur: 10,
          shadowOffsetY: 5
        },
        itemStyle: {
          color: '#e74c3c',
          borderWidth: 2,
          borderColor: '#fff'
        },
        label: {
          show: true,
          position: 'top',
          formatter: (params: any) => {
            return `¥${params.value.toLocaleString()}`
          },
          color: '#e74c3c',
          fontWeight: 'bold'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

onMounted(() => {
  getMonthlyCountStats()
  getMonthlyCostStats()
})
</script>

<template>
  <el-card class="card-box">
    <div class="header">
      <h2>维修统计分析</h2>
    </div>
    
    <div class="chart-container">
      <div class="chart-row">
        <div class="chart-item">
          <div ref="countChartRef" class="chart"></div>
        </div>
        <div class="chart-item">
          <div ref="costChartRef" class="chart"></div>
        </div>
      </div>
      <div class="chart-row">
        <div class="chart-item full-width">
          <div ref="combinedChartRef" class="chart"></div>
        </div>
      </div>
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.card-box {
  width: 100%;
  max-width: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  padding: 0;
  overflow: hidden;
}

.header {
  padding: 0.8rem 1.2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e6eaf0;
  background-color: #f7f9fc;
  
  h2 {
    font-weight: 600;
    font-size: 1.4rem;
    color: #333;
    user-select: none;
    margin: 0;
  }
}

.chart-container {
  padding: 1rem;
}

.chart-row {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
  
  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.chart-item {
  flex: 1;
  height: 300px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  }
  
  &.full-width {
    flex: 0 0 100%;
    height: 350px;
  }
}

.chart {
  width: 100%;
  height: 100%;
}
</style>